<?php
require_once("../data/common.php");


header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
Header("Content-type: application/vnd.google-earth.kml+xml");


$template = new STE();
$template->load("kml");

	if ($user->logged_in == FALSE)
		$sql = "SELECT * FROM gps_current_location LEFT JOIN (users, users_devices) ON (gps_current_location.device_id=users_devices.id AND users_devices.user_id=users.id) WHERE UNIX_TIMESTAMP(time_received) > ( UNIX_TIMESTAMP() - 2592000 ) AND visibility <> 0 ORDER BY username;";
	else	$sql = "SELECT * FROM gps_current_location LEFT JOIN (users, users_devices) ON (gps_current_location.device_id=users_devices.id AND users_devices.user_id=users.id) WHERE UNIX_TIMESTAMP(time_received) > ( UNIX_TIMESTAMP() - 2592000 ) ORDER BY username;";
	$stmt = $dbh->prepare($sql);
	$stmt->execute();

	$variables["PLACEMARKS"] = "";
	$rows = $stmt->fetchAll();
	foreach ($rows as $rs) {
		if ( ( (time()-strtotime( $rs["time_received"]) )/60) < 10) {
			$active = 1;
			$icon = "onlineStyle";
		} else { 
			$active = 0;
			$icon = "offlineStyle";
		}
		if($user->logged_in == TRUE)
		{
		$variables["PLACEMARKS"] .= sprintf('  <Placemark>
	    <name>%s</name>
	    <device>%s</device>
	    <description><![CDATA[
		User: %s<br />
		Path: <a href="#" onclick="loadKML(\'%s\')">6h</a>/<a href="#" onclick="loadKML(\'%s\')">12h</a>/<a href="#" onclick="loadKML(\'%s\')">24h</a><br />
		Time received: %s<br />
		Altitude: %s m<br />
		Speed: %s km/h<br />
		Course: %s<br />
		Active: %s<br />
		Location: %s, %s<br />
		]]></description>
	    <styleUrl>#%s</styleUrl>
	    <Point>
	      <coordinates>%s,%s,0</coordinates>
	    </Point>
	  </Placemark>
	', 
		$rs["username"],
		$rs["device_id"],
		$rs["username"],
		$site_url."/xml-old.php?track=1&device=".$rs["device_id"]."&hours=6&type=kml",
		$site_url."/xml-old.php?track=1&device=".$rs["device_id"]."&hours=12&type=kml",
		$site_url."/xml-old.php?track=1&device=".$rs["device_id"]."&hours=24&type=kml",
		$rs["time_received"],
		round($rs["alt"]*0.3048,0),
		round($rs["speed"]*1.852,1),
		$rs["course"],
		$active,
		$rs["lat"],
		$rs["lon"],
		$icon,
		$rs["lon"],
		$rs["lat"]	
		);
		}
		else {
			$variables["PLACEMARKS"] .= sprintf('  <Placemark>
	    <name>N/A</name>
	    <device>%s</device>
	    <description><![CDATA[
		User: N/A<br />
		Time received: %s<br />
		Altitude: %s m<br />
		Speed: %s km/h<br />
		Course: %s<br />
		Active: %s<br />
		Location: %s, %s<br />
		]]></description>
	    <styleUrl>#%s</styleUrl>
	    <Point>
	      <coordinates>%s,%s,0</coordinates>
	    </Point>
	  </Placemark>
	', 
		$rs["device_id"],
		$rs["time_received"],
		round($rs["alt"]*0.3048,0),
		round($rs["speed"]*1.852,1),
		$rs["course"],
		$active,
		$rs["lat"],
		$rs["lon"],
		$icon,
		$rs["lon"],
		$rs["lat"]	
		);
		}
	}

	$template->assign($variables);
	print $template->display();

?>
